package com.example.baiduapi.serviceListener.newListerner.config;

import com.alibaba.fastjson.JSONObject;
import com.example.baiduapi.domain.AjaxResult;
import com.example.baiduapi.serviceListener.service.MvcService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class ListenerConfig {
    @Autowired
    private ApplicationContext applicationContext;

    private static final Map<String, MvcService> mvcMaps = new HashMap<>();

    @PostConstruct
    public void registerService(){
        String[] beanNames = applicationContext.getBeanNamesForType(MvcService.class);
        for (String beanName : beanNames) {
            MvcService listener = applicationContext.getBean(beanName, MvcService.class);
            Class<?> listenerClass = listener.getClass();
            if (listenerClass.isAnnotationPresent(com.example.baiduapi.serviceListener.newListerner.config.ServiceNameEvent.class)){
                com.example.baiduapi.serviceListener.newListerner.config.ServiceNameEvent serviceNameEvent = listenerClass.getAnnotation(com.example.baiduapi.serviceListener.newListerner.config.ServiceNameEvent.class);
                String servicName = serviceNameEvent.beanName();
                mvcMaps.put(servicName,listener);
            }

        }
    }
    /**
     * 实现多版本切换
     * @param serviceName 服务名称
     * @param eventData  数据
     */
    public AjaxResult dispatchEvent(String serviceName, JSONObject eventData){
        try {
            MvcService mvcService = mvcMaps.get(serviceName);
            if (mvcService == null){
                log.error("未找到对应服务:{}",serviceName);
                return AjaxResult.error("未找到对应的服务："+serviceName+"，请检查服务名是否存在或是否使用ServiceNameEvent注解注入");
            }
            return mvcService.mvcFunction(eventData);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("服务调用异常：{}", ExceptionUtils.getStackTrace(e));
            throw new RuntimeException(e);
        }
    }
}
